package user

import (
	"chaowan/data_source"
	"chaowan/models"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	appidgzh     = "wx558cf871bb15db07"
	appsecretgzh = "0558c8f49790db53518b35fa924adf0c"
	appid        = "wxefb45719a26251de"
	appsecret    = "6bde284e7ea3a0f723bcfe381cd73b9d"
)

func Logingzh(ctx *gin.Context) {
	json1 := KDRespBody{}
	ctx.ShouldBind(&json1)
	code := json1.Code
	open := Accesstoken4(code)
	qudao := json1.Qudao
	//fmt.Println(open)
	//return
	openid := open.Openid
	unionid := open.Unionid
	weixin := Accesstokengzh(openid, open.AccessToken)
	if weixin.Openid == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "授权失败",
		})
		return
	}
	reqip := ctx.ClientIP()
	var uid int64
	var user models.User
	data_source.Db.Where("unionid = ?", unionid).First(&user)
	if user.ID > 0 {
		upuser1 := models.User{
			LoginIp:   reqip,
			LoginTime: time.Now().Unix(),
			LoginNum:  user.LoginNum + 1,
			Newuser:   2,
		}
		data_source.Db.Where("unionid = ?", unionid).Updates(upuser1)
		uid = user.ID
	} else {
		var user1 models.User
		data_source.Db.Where("gzh_openid = ?", openid).First(&user1)
		if user1.ID > 0 {
			upuser := models.User{
				LoginTime: time.Now().Unix(),
				LoginIp:   reqip,
				LoginNum:  user.LoginNum + 1,
				Newuser:   2,
			}
			data_source.Db.Where("gzh_openid = ?", openid).Updates(upuser)
		} else {
			adduser := models.User{
				LoginTime:  time.Now().Unix(),
				LoginIp:    reqip,
				GzhOpenid:  openid,
				CreateTime: time.Now().Unix(),
				LoginNum:   1,
				Logo:       weixin.Headimgurl,
				Nickname:   weixin.Nickname,
				Unionid:    unionid,
				Newuser:    1,
				Vip:        1,
				Qudao:      qudao,
			}
			data_source.Db.Create(&adduser)
			uid = adduser.ID
		}
	}

	var usernew models.User
	data_source.Db.Where("id = ?", uid).Where("status = 1").First(&usernew)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    usernew,
		"msg":     "ok",
	})
	return
}

type Responseuser struct {
	Nickname   string `json:"nickname"`
	Headimgurl string `json:"headimgurl"`
	Openid     string `json:"openid"`
	Province   string `json:"province"`
	Unionid    string `json:"unionid"`
}

func Accesstokengzh(openid, access_token string) (data Responseuser) {

	resp, err := http.Get("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN")
	//fmt.Println(code)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responseuser{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type ResponseOpenid struct {
	AccessToken string `json:"access_token"`
	Openid      string `json:"openid"`
	Unionid     string `json:"unionid"`
	Ticket      string `json:"ticket"`
}

func Accesstoken4(code string) (data ResponseOpenid) {
	resp, err := http.Get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appidgzh + "&secret=" + appsecretgzh + "&code=" + code + "&grant_type=authorization_code")
	//fmt.Println(code)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := ResponseOpenid{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}
